import sys,os
from lowlevel import *
from mutagen.mp3 import MP3
from mutagen.id3 import TPE1
import Levenshtein,urllib,urllib2
API_Key="59a5d7fa32f755407c332cb79e4ddbf4"
secret="f6820c1d8e4f0e6d6d69ea7ec4a01578"
api_url="http://ws.audioscrobbler.com/2.0/?api_key="+API_Key+"&method="
autocorrect="&autocorrect=1&"
def kickfeat(passed):
                passed=passed.lower()
                if("ft." in passed):
                   passed=passed[:passed.find("ft.")]     
		if(" ft" in passed):						##C# Modify Tags containting "Featuring" or such
		   passed=passed[:passed.find(" ft")]			#
		if(" feat" in passed):									#
		   passed=passed[:passed.find(" feat")]
		if("," in passed):									#
		   passed=passed[:passed.find(",")]
		if("feat" in passed)and ("defeat" not in passed):	#
		   passed=passed[:passed.find("feat")]
		passed=passed.rstrip()
		return passed

def getfield(fname,query,pointsto=0):
                first=query.find("<"+fname+">",pointsto)+len(fname)+2
		firstwordofname=""
		for letter in fname:
			if(letter==" "):
				break
			
			firstwordofname=firstwordofname+letter
		second=query.find("</"+firstwordofname+">",first)
		if (first==-1 or second==-1):
                        return ""
		return (query[first:second],second)
def eraseinfo(target):
        audio=MP3(target)
	try:
		audio.__delitem__('APIC:Cover')
		print "deleted cover"
	except:
            print "couldnt delete cover"
            donothing=1
	try:
		audio.__delitem__('TCON')
	except:donothing=1
	try:
		audio.__delitem__('TALB')
	except:donothing=1
	audio.save()

var=raw_input("What do you want to do?\n>>>")
if(var=="trackinfo"):
	artist=raw_input("Specify an Artist: ")
	track=raw_input("Specify a Track: ")
	print urllib2.urlopen(Ant.api_url+"track.getinfo"+Ant.autocorrect+"artist="+urllib.quote_plus(artist)+"&track="+urllib.quote_plus(track)).read()
if(var=="eraseall"):
        var=raw_input("Specify a folder")
        for item in airborne(os.path.abspath(var)):
                if("mp3" in item):
                        try:
                                eraseinfo(item)
                        except: continue
if(var=="matchartists"):
        with open('ref.txt','r') as f:
                cont=f.readlines()
        temp=list()
        for item in sorted(cont):
                temp.append(item[:item.find("\r")])
        for item in temp:
                maxval=0.9
                flag=0
                maxname=""
                for compare in temp:
                        sim=Levenshtein.ratio(item,compare)
                        if(sim>maxval and sim!=1):
                                flag=1
                                maxval=sim
                                maxname=compare
                if(flag==1):
                        print (item+" vs "+maxname +" with "+str(maxval))
                try:
                        cor=getfield("name",urllib2.urlopen(api_url+"artist.getCorrection"+autocorrect+"artist="+urllib.quote_plus(item)).read())
                        if (cor!=""):
                                print item+" vs "+cor[0]
                except: pass
if(var=="correctartists"):
    var=raw_input("Specify a folder")
    for item in airborne(os.path.abspath(var)):
        if(".mp3" in item and "mpg" not in item):
            try:audio=MP3(item)
            except IOError:
                        print("Cannot access file "+item+" probably because of name contains non-ascii chars")
                        continue
            try:artist=kickfeat(audio['TPE1'][0].lower())
	    except KeyError:continue
	try:
            cor=getfield("name",urllib2.urlopen(api_url+"artist.getCorrection"+autocorrect+"artist="+urllib.quote_plus(artist)).read())
            if (cor!=""):
                if("&amp" in cor[0]):
                    corri=cor[0][:cor[0].find("&")]+"&"+cor[0][cor[0].find("&")+5:]
                    print "!!!"
                else:
                    corri=cor[0]
                print (corri+"  versus original "+artist)
        except urllib2.HTTPError:continue
        except KeyError:continue
        except :continue
if(var=="eraseinfo"):
	eraseinfo(sys.argv[1])
if(var=="getinfo"):
	audio=MP3(sys.argv[1])
	taglist=['APIC:Cover','TPE1','TIT2','TALB','TCON']
	for item in taglist:
		try:
			print(audio.__getitem__(item))
		except:
			print("Item: "+item+" was not found")
	audio.save()
if(var=="restoreartists"):
        var=raw_input("Specify a folder")
        for item in airborne(os.path.abspath(var)):
                if(".mp3" in item and "mpg" not in item):
                        try:
                                if(" - " in item):
                                        audio=MP3(item)
                                        audio.tags.add(TPE1(encoding=3, text=unicode(item[item.rfind("\\")+1:item.find(" - ")]).decode('latin-1')))
                                        audio.save()
                                        del audio
                        except:continue
if(var=="test"):
    import pylast

    # You have to have your own unique two values for API_KEY and API_SECRET
    # Obtain yours from http://www.last.fm/api/account for Last.fm
    API_KEY="59a5d7fa32f755407c332cb79e4ddbf4"
    API_SECRET="f6820c1d8e4f0e6d6d69ea7ec4a01578"

    # In order to perform a write operation you need to authenticate yourself
    username = "Arpheno"
    password_hash = pylast.md5("9.1g2-")

    network = pylast.get_lastfm_network(api_key = API_Key, api_secret = 
        secret, username = username, password_hash = password_hash)

    track = network.get_track("Iron Maiden", "The Nomad")
    album=track.get_album()
    print album.get_cover_image()
    print urllib2.urlopen(album.get_cover_image()).read()

    # type help(pylast.LastFMNetwork) or help(pylast) in a python interpreter to get more help
    # about anything and see examples of how it works
        
        
